package com.qinglian.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qinglian.entity.User;
import com.qinglian.mapper.UserMapper;
import com.qinglian.service.IUserService;
import com.qinglian.utils.RedisUtil;
import com.qinglian.utils.Result;
import com.qinglian.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author augn
 * @since 2023-04-14
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper mapper;

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public Result<?> register(String account, String password, Integer code) {

        Integer userCode = (Integer) redisUtil.get("code" + account);
        if (Objects.equals(userCode, code)) {
            User user = new User();

            user.setAccount(account);
            user.setPassword(password);
            user.setName("新用户");
            user.setImage("");
            mapper.insert(user);
            return Result.success(user);
        } else {
            return Result.error("-1","验证码错误");
        }

    }

    // 用户登录
    @Override
    public Result<?> login(String account, String password) {

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.and(i -> i.eq("account", account).eq("password", password));
        List<User> users = mapper.selectList(wrapper);
        int count = users.size();
        if (count == 1) {
            Map<String, Object> map = new HashMap<>();
            String token = tokenUtil.getToken(users.get(0).getId());
            map.put("image", users.get(0).getImage());
            map.put("userId", users.get(0).getId());
            map.put("account",users.get(0).getAccount());
            map.put("name",users.get(0).getName());
            map.put("personalSignature",users.get(0).getPersonalSignature());
            map.put("token", token);

            redisUtil.set("token" + users.get(0).getId(), token);
            return Result.success(map);

        } else {
            return Result.error("-1", "账号或密码错误");
        }
    }

    // 更新用户
    @Override
    public Result<?> update(User user) {
        user.setPassword(null);
        int update = mapper.updateById(user);
        if (update == 0) {
            return Result.error("-1", "更新失败");
        } else {
            return Result.success(update);
        }
    }

    @Override
    public Result<?> getUserByAccount(Integer userId) {
        User user = mapper.selectById(userId);
        if(user != null) {
            return Result.success(user);
        } else {
            return Result.error("-1", "无此用户");
        }
    }

}
